﻿using _3._0检查.Model;
using System;
using System.Collections.Generic;
using System.Text;
using Mysoft.Utility;
using System.Linq;
using System.IO;
using System.Reflection;

namespace _3._0检查.Business.检查domain的非internal方法
{
    internal class Main
    {
        GitHelper gitHelper = new GitHelper();
        public List<CheckResult> Fx()
        {
            var sys = Model.AppSettings.CheckSys.Instance;
            //1、获取代码
            gitHelper.Clone(sys.GitUrl, sys.Feature, FeatureTypeEnum.Feature);
            //2、编译代码
            var src = gitHelper.GetSrcPath();

            List<CheckResult> results = new List<CheckResult>();
            //检查多语言
            results.AddRange(CheckDyy(src));
            //检查枚举、handle
            results.AddRange(CheckEnumHandle(src + "\\00_根目录\\_metadata"));

            RumCmdHelper.RumCmd("cd /d " + src + "&" + "100_PullAndBuild.cmd");
            //var src = @"D:\gitee\自写工具\src\erp各种检查\3.0检查\bin\Debug\netcoreapp3.1\Git\a34d8248-df1a-4fe9-a4e0-e808a8255e4f\slxt_xsbg\src";
            //3、检查
            results.AddRange(GetModels(src + "\\00_根目录\\bin", sys.CheckDll));

            //4、删除文件 
            new System.Threading.Tasks.Task(() =>
            {
                System.Threading.Thread.Sleep(5000);
                PathHelper.DeletePath(gitHelper.GetRootPath());
            }).Start();

            return results;
        }

        /// <summary>
        /// 获取所有业务模块的方法
        /// </summary>
        /// <returns></returns>
        private List<CheckResult> GetModels(string binAddress, string dllFilter)
        {
            List<CheckResult> checkResults = new List<CheckResult>();
            var dlls = Directory.GetFiles(binAddress).Where(t => t.Contains(dllFilter)).Where(t => t.EndsWith(".dll"));
            //获取dll的物理路径
            foreach (var dll in dlls)
            {
                Assembly ass = Assembly.LoadFrom(dll);
                List<Type> typeList = ass.GetTypes().ToList();
                var domainTypeList = typeList.Where(p => p.BaseType != null && p.BaseType.Name == "BusinessUnitDomainService");
                foreach (var domainType in domainTypeList)
                {
                    if (domainType.IsPublic == true)
                    {
                        checkResults.Add(new CheckResult
                        {
                            Title = "domain的修饰符不能为public",
                            Content = "问题类：" + domainType.FullName
                        });
                    }
                }
            }
            return checkResults;
        }

        private static readonly List<string> SlPre = new List<string> {
        "Mysoft.Slxt.ProjectPrep","Mysoft.Slxt.Common","Mysoft.Slxt.PriceMng","Mysoft.Slxt.TradeMng","Mysoft.Slxt.FinanceMng","Mysoft.Slxt.SaleService","Mysoft.Slxt.OpportunityMng","Mysoft.Slxt.Scyx"
        };

        //验证枚举和handle
        private List<CheckResult> CheckEnumHandle(string path)
        {
            List<CheckResult> results = new List<CheckResult>();
            var files = GetFile(path);
            // 1、erp的枚举： 2.0Mysoft.Slxt.变更单元：Mysoft.Slxt.Xsbg.  <enum enumTypeName="Mysoft.Slxt.Common.Model.Enums.SlxtModiTypeEnum" />
            //2、handler:Mysoft.Slxt.Xsbg：<pageHandler pageHandlerId="Mysoft.Slxt.Xsbg.Common.Handler.FindAppointmentTextBoxListHandler,Mysoft.Slxt.Xsbg.Common" method="Load" extMethod="" />
            foreach (var file in files)
            {
                var text = System.IO.File.ReadAllText(file.FilePath, Encoding.Default);
                foreach (var key in SlPre)
                {
                    if (text.IndexOf(key) > -1)
                    {
                        results.Add(new CheckResult
                        {
                            Title = "使用到售楼的命名空间" + key,
                            Content = "使用到售楼的命名空间" + key + "，文件：" + file.FileName + "(可能是枚举或者handler)"
                        });
                    }
                }
            }
            return results;
            //4、js：线上js不存在问题
        }

        //验证多语言
        private List<CheckResult> CheckDyy(string path)
        {
            List<CheckResult> results = new List<CheckResult>();
            //3、多语言{##[lang:L0011_00110600_Trade_HjAddress]##}
            GetGnbLang getGnbLang = new GetGnbLang();
            var noContainLang = getGnbLang.GetLangList(path);
            foreach (var lang in noContainLang)
            {
                results.Add(new CheckResult
                {
                    Title = "功能包中未定义多语言key：" + lang,
                    Content = "功能包中未定义多语言key" + lang + "（可能直接使用了ERP的多语言）"
                });
            }

            return results;
        }

        private List<FileDto> GetFile(string path)
        {
            List<FileDto> fileDtos = new List<FileDto>();

            DirectoryInfo dic = new DirectoryInfo(path);

            foreach (var file in dic.GetFiles())
            {
                fileDtos.Add(new FileDto
                {
                    FileInfo = file,
                    FilePath = file.FullName,
                    FileName = file.Name
                });
            }

            foreach (var dir in dic.GetDirectories())
            {
                //临时修改的文件不要放进来
                if (dir.FullName.EndsWith("src\05_售楼修改"))
                {
                    continue;
                }
                fileDtos.AddRange(GetFile(dir.FullName));
            }
            return fileDtos;
        }
    }
}
